﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Navigation;
using System.Windows.Threading;
using DiagnosticCenter.ViewModel;
using DiagnosticCenter.Web;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.TransitionControl;
using ItemsControl = System.Windows.Controls.ItemsControl;

namespace DiagnosticCenter.View
{
    public partial class viewWelcome : Page
    {

        public viewWelcome()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {

        }

        private void buttonLogin_Click(object sender, RoutedEventArgs e)
        {
            var strLogin = textLogin.Text.Trim();
            var strPassword = textPassword.Password.Trim();
            vmTools.DoLogin(strLogin, strPassword);
        }
    }

    #region Rotator
    public static class RotatorExtensions
    {
        public static readonly DependencyProperty ItemsSourceProperty =
            DependencyProperty.RegisterAttached("ItemsSource", typeof(IEnumerable), typeof(RotatorExtensions), new PropertyMetadata(null, OnItemsSourceChanged));

        public static readonly DependencyProperty ItemChangeDelayProperty =
            DependencyProperty.RegisterAttached("ItemChangeDelay", typeof(Duration), typeof(RotatorExtensions), new PropertyMetadata(new Duration(TimeSpan.FromSeconds(0.3))));

        public static readonly DependencyProperty CurrentSelectedIndexProperty =
            DependencyProperty.RegisterAttached("CurrentSelectedIndex", typeof(int), typeof(RotatorExtensions), new PropertyMetadata(-1, OnCurrentSelectedIndexChanged));

        private static readonly DependencyProperty TimerProperty =
            DependencyProperty.RegisterAttached("Timer", typeof(DispatcherTimer), typeof(RotatorExtensions), null);

        public static IEnumerable GetItemsSource(DependencyObject obj)
        {
            return (IEnumerable)obj.GetValue(ItemsSourceProperty);
        }

        public static void SetItemsSource(DependencyObject obj, IEnumerable value)
        {
            obj.SetValue(ItemsSourceProperty, value);
        }

        public static Duration GetItemChangeDelay(DependencyObject obj)
        {
            return (Duration)obj.GetValue(ItemChangeDelayProperty);
        }

        public static void SetItemChangeDelay(DependencyObject obj, Duration value)
        {
            obj.SetValue(ItemChangeDelayProperty, value);
        }

        public static int GetCurrentSelectedIndex(DependencyObject obj)
        {
            return (int)obj.GetValue(CurrentSelectedIndexProperty);
        }

        public static void SetCurrentSelectedIndex(DependencyObject obj, int value)
        {
            obj.SetValue(CurrentSelectedIndexProperty, value);
        }

        private static DispatcherTimer GetTimer(DependencyObject obj)
        {
            return (DispatcherTimer)obj.GetValue(TimerProperty);
        }

        private static void SetTimer(DependencyObject obj, DispatcherTimer value)
        {
            obj.SetValue(TimerProperty, value);
        }

        private static void OnCurrentSelectedIndexChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            UpdateCurrentlySelectedItem(d);
        }

        private static void MoveToNextElement(DependencyObject element)
        {
            IEnumerable source = GetItemsSource(element);
            if (source != null)
            {
                IEnumerable<object> convertedSource = source.Cast<object>();
                int currentIndex = GetCurrentSelectedIndex(element);

                currentIndex = ++currentIndex % convertedSource.Count();
                SetCurrentSelectedIndex(element, currentIndex);
            }
        }

        private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var element = d as FrameworkElement;
            var itemsControl = d as ItemsControl;

            var oldValue = e.OldValue as IEnumerable;
            var newValue = e.NewValue as IEnumerable;

            if (element != null)
            {
                if (oldValue != null)
                {
                    // Detach the Ad Rotator functionality.
                    element.Loaded -= OnElementLoaded;
                    element.Unloaded -= OnElementUnloaded;

                    // If there is a timer attached, stop it.
                    DispatcherTimer timer = GetTimer(element);
                    if (timer != null)
                    {
                        timer.Stop();
                    }
                }

                if (newValue != null)
                {
                    // Attach the Ad Rotator functionality.
                    element.Loaded += OnElementLoaded;
                    element.Unloaded += OnElementUnloaded;

                    // If the target is an ItemsControl and its ItemsSource is not set, set it.
                    if (itemsControl != null && itemsControl.ItemsSource == null && itemsControl.Items.Count == 0)
                    {
                        itemsControl.ItemsSource = newValue;
                    }
                }
            }
        }

        private static DependencyObject element;

        private static void OnElementLoaded(object sender, RoutedEventArgs args)
        {
            element = sender as DependencyObject;

            // Create the timer and hook-up to the events.
            var timer = new DispatcherTimer { Interval = GetItemChangeDelay(element).TimeSpan };
            SetTimer(element, timer);

            timer.Tick += new EventHandler(timer_Tick);

            timer.Start();

            // Make sure the currently pointed element is selected.
            UpdateCurrentlySelectedItem(element);
        }

        static void timer_Tick(object sender, EventArgs e)
        {
            MoveToNextElement(element);
        }

        private static void OnElementUnloaded(object sender, RoutedEventArgs args)
        {
            var element = sender as FrameworkElement;

            GetTimer(element).Stop();
        }

        private static void UpdateCurrentlySelectedItem(DependencyObject element)
        {
            var contentControl = element as ContentControl;

            IEnumerable source = GetItemsSource(element);

            // If there is no source we shouldn't do anything.
            if (source == null) return;

            // Find the actual index to be selected (if outside the boundaries of the collection)
            // and find the actual element to be selected.
            IEnumerable<object> convertedSource = source.Cast<object>();
            int currentIndex = GetCurrentSelectedIndex(element);
            object elementToSelect = convertedSource.ElementAtOrDefault(currentIndex);

            // Update the cotnent of the ContentControl if attached to a ContentControl.
            if (contentControl != null)
            {
                contentControl.Content = elementToSelect;
            }
        }
    }

    public class RotatorItemsCollection : ObservableCollection<object>
    {

    }

    #endregion


    #region AuthorCard

    public class Person : ViewModelBase
    {

        private string _DisplayName;
        public string DisplayName
        {
            get
            {
                return _DisplayName;
            }
            set
            {
                if (value != _DisplayName)
                {
                    _DisplayName = value;
                    OnPropertyChanged(() => DisplayName);
                }
            }
        }

        private ImageSource _Photo;
        public ImageSource Photo
        {
            get
            {
                return _Photo;
            }
            set
            {
                if ((object)_Photo != (object)value)
                {
                    _Photo = value;
                    OnPropertyChanged(() => Photo);
                }
            }
        }

        private string _EMail;
        public string EMail
        {
            get
            {
                return _EMail;
            }
            set
            {
                if (value != _EMail)
                {
                    _EMail = value;
                    OnPropertyChanged(() => EMail);
                }
            }
        }

        private string _Company;
        public string Company
        {
            get
            {
                return _Company;
            }
            set
            {
                if (value != _Company)
                {
                    _Company = value;
                    OnPropertyChanged(() => Company);
                }
            }
        }

        private string _Position;
        public string Position
        {
            get
            {
                return _Position;
            }
            set
            {
                if (value != _Position)
                {
                    _Position = value;
                    OnPropertyChanged(() => Position);
                }
            }
        }
    }



    public class BusinessCards : ViewModelBase, ISupportInitialize
    {
        public BusinessCards()
        {
            SelectNext = new DelegateCommand(SelectNextPerson);
            SelectPrevious = new DelegateCommand(SelectPreviousPerson);
            currentTransitionIndex = -1;

            _Persons = new ObservableCollection<Person>();
            _Transitions = new ObservableCollection<TransitionSet>();
        }

        private int currentTransitionIndex;

        private void SelectNextPerson(object param)
        {
            if (Persons != null && Persons.Count() > 1)
            {
                SelectNextForwardTransition();

                int index = Persons.IndexOf(SelectedPerson);
                index++;
                if (index >= Persons.Count())
                {
                    index = 0;
                }
                SelectedPerson = Persons[index];
            }
        }

        private void SelectNextForwardTransition()
        {
            if (Transitions != null && Transitions.Count() > 0)
            {
                currentTransitionIndex++;
                if (currentTransitionIndex >= Transitions.Count())
                {
                    currentTransitionIndex = 0;
                }
                CurrentTransition = Transitions[currentTransitionIndex].ForwardTransition;
            }
            else
            {
                CurrentTransition = null;
            }
        }

        private void SelectPreviousPerson(object param)
        {
            if (Persons != null && Persons.Count() > 1)
            {
                SelectPreviousBackwardTransition();

                int index = Persons.IndexOf(SelectedPerson);
                index--;
                if (index < 0)
                {
                    index = Persons.Count() - 1;
                }
                SelectedPerson = Persons[index];
            }
        }

        private void SelectPreviousBackwardTransition()
        {
            if (Transitions != null && Transitions.Count() > 0)
            {
                CurrentTransition = Transitions[currentTransitionIndex].BackwardTransition;
                currentTransitionIndex--;
                if (currentTransitionIndex < 0)
                {
                    currentTransitionIndex = Transitions.Count() - 1;
                }
            }
            else
            {
                CurrentTransition = null;
            }
        }

        private TransitionProvider _CurrentTransition;
        public TransitionProvider CurrentTransition
        {
            get
            {
                return _CurrentTransition;
            }
            private set
            {
                if (value != _CurrentTransition)
                {
                    _CurrentTransition = value;
                    OnPropertyChanged("CurrentTransition");
                }
            }
        }

        public ICommand SelectNext { get; private set; }

        public ICommand SelectPrevious { get; set; }

        private Person _SelectedPerson;
        public Person SelectedPerson
        {
            get
            {
                return _SelectedPerson;
            }
            set
            {
                if (_SelectedPerson != value)
                {
                    _SelectedPerson = value;
                    OnPropertyChanged("SelectedPerson");
                }
            }
        }


        private ObservableCollection<TransitionSet> _Transitions;
        public ObservableCollection<TransitionSet> Transitions
        {
            get
            {
                return _Transitions;
            }
        }

        private ObservableCollection<Person> _Persons;
        public ObservableCollection<Person> Persons
        {
            get
            {
                return _Persons;
            }
        }

        public void BeginInit()
        {
        }

        public void EndInit()
        {
            if (Persons != null && Persons.Count() > 0)
            {
                SelectedPerson = Persons.FirstOrDefault();
            }
        }
    }

    public class TransitionSet : ViewModelBase
    {
        private TransitionProvider _ForwardTransition;
        public TransitionProvider ForwardTransition
        {
            get
            {
                return _ForwardTransition;
            }
            set
            {
                if (_ForwardTransition != value)
                {
                    _ForwardTransition = value;
                    OnPropertyChanged(() => ForwardTransition);
                }
            }
        }

        private TransitionProvider _BackwardTransition;
        public TransitionProvider BackwardTransition
        {
            get
            {
                return _BackwardTransition;
            }
            set
            {
                if (_BackwardTransition != value)
                {
                    _BackwardTransition = value;
                    OnPropertyChanged(() => BackwardTransition);
                }
            }
        }
    }


    #endregion
}
